﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Security;

namespace Controller2.Models.ViewModels
{
    public class AccountViewModel
    {
        public string UserName { get; set; }
        public int? IdPessoa { get; set; }
        public string Nome { get; set; }
        public string DataCadastro { get; set; }
        public string Role { get; set; }

        public IEnumerable<AccountViewModel> Listar(ControllerBDModelContainer db)
        {
            var users = new List<MembershipUser>();
            foreach (MembershipUser i in Membership.GetAllUsers())
            {
                users.Add(i);
            }

            var dados = (from u in users
                         join p in db.Pessoa.ToList() on u.UserName equals p.UserName into
                         up
                         from x in up.DefaultIfEmpty()
                         select new
                         {
                             UserName = u.UserName,
                             IdPessoa = x == null ? (int?)null : x.IdPessoa,
                             NomePessoa = x == null ? null : x.NomePessoa,
                             DataCad = x == null ? null : x.DataCadastro.ToShortDateString(),
                             Role = Roles.GetRolesForUser(u.UserName)
                         }).ToList().Select(s => new AccountViewModel
                            {
                                UserName = s.UserName,
                                IdPessoa = s.IdPessoa,
                                Nome = s.NomePessoa,
                                DataCadastro = s.DataCad,
                                Role = s.Role.FirstOrDefault()
                            });
			return dados.OrderBy(o => o.UserName);
        }
    }
}